﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Advert;
using Nop.Admin.Models.Advert;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Advert;
using Nop.Services.Logging;
using Nop.Services.Security;
using Nop.Web.Framework.Controllers;
using Telerik.Web.Mvc;

namespace Nop.Admin.Controllers
{
     [AdminAuthorize]
    public class AdvertController : BaseNopController
    {
        #region Fields
        private readonly IAdvertisementService _advertisementService;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly ILanguageService _languageService;
        private readonly ILocalizationService _localizationService;
        private readonly PdfSettings _pdfSettings;
        private readonly ILocalizedEntityService _localizedEntityService;
        private readonly ICustomerActivityService _customerActivityService;
        #endregion Fields

        #region Advert

        public AdvertController( IAdvertisementService advertisementService,IPermissionService permissionService,
            AdminAreaSettings adminAreaSettings,ILanguageService languageService,
            ILocalizationService localizationService, PdfSettings pdfSettings, 
            ILocalizedEntityService localizedEntityService,ICustomerActivityService customerActivityService
            )
        {
            this._advertisementService = advertisementService;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
            this._languageService = languageService;
            this._localizationService = localizationService;
            this._pdfSettings = pdfSettings;
            this._localizedEntityService = localizedEntityService;
            this._customerActivityService = customerActivityService;
        }

        #endregion 

        #region List
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAdvert))
                return AccessDeniedView();

            var advert = _advertisementService.GetAllAdvertisement(null, null, 0, _adminAreaSettings.GridPageSize, true);
            AdvertisementListModel model = new AdvertisementListModel();
            model.Advertisement = new GridModel<AdvertisementModel>
            {
                Data = advert.Select(x =>
                {
                    var m = x.ToModel();
                    return m;
                }),
                Total = advert.TotalCount
            };
            return View(model);
        }

        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult List(GridCommand command, AdvertisementListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAdvert))
                return AccessDeniedView();

            var advert = _advertisementService.GetAllAdvertisement(null,null,
                command.Page - 1, command.PageSize, true);
            var gridModel = new GridModel<AdvertisementModel>
            {
                Data = advert.Select(x =>
                {
                    var advertModel = x.ToModel();
                    return advertModel;
                }),
                Total = advert.TotalCount
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }
        #endregion

        #region Create / Edit / Delete

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return AccessDeniedView();

            var model = new AdvertisementModel();
            
            PrepareAdvertType(model);
            return View(model);
        }

        [HttpPost, FormValueExists("save", "save-continue", "continueEditing")]
        public ActionResult Create(AdvertisementModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAdvert))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                var advert = model.ToEntity();
                advert.CreatedOnUtc = DateTime.UtcNow;
                advert.Published = true; //默认为已发布
                _advertisementService.InsertAdvertisement(advert);
                //locales
                UpdateLocales(advert, model);


                //activity log
                _customerActivityService.InsertActivity("AddNewAdvertisement", _localizationService.GetResource("ActivityLog.AddNewAdvertisement"), new { advert.Name,advert.Id });

                SuccessNotification(_localizationService.GetResource("Admin.Advert.Manufacturers.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = advert.Id }) : RedirectToAction("List");
            }

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAdvert))
                return AccessDeniedView();

            var advert = _advertisementService.GetAdvertisementById(id);
            if (advert == null || advert.Deleted || advert.StartTime <= DateTime.Now)
                //No category found with the specified id
                return RedirectToAction("List");

            var model = advert.ToModel();

            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.Name = advert.GetLocalized(x => x.Name, languageId, false, false);
                locale.Description = advert.GetLocalized(x => x.Description, languageId, false, false);

            });
            //advertType
            PrepareAdvertType(model);

            return View(model);
        }

        [HttpPost, FormValueExists("save", "save-continue", "continueEditing")]
        public ActionResult Edit(AdvertisementModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return AccessDeniedView();

            var advert = _advertisementService.GetAdvertisementById(model.Id);
            if (advert == null || advert.Deleted || advert.StartTime <= DateTime.Now)
                //No category found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                advert = model.ToEntity(advert);
                //advert.UpdatedOnUtc = DateTime.UtcNow;
                _advertisementService.UpdateAdvertisement(advert);
                //locales
                UpdateLocales(advert, model);

                //activity log
                _customerActivityService.InsertActivity("EditAdvert", _localizationService.GetResource("ActivityLog.EditAdvert"), advert.Name);

                SuccessNotification(_localizationService.GetResource("Admin.Advert.Advertisement.Updated"));
                return continueEditing ? RedirectToAction("Edit", advert.Id) : RedirectToAction("List");
            }


            //advertType
            PrepareAdvertType(model);
            return View(model);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return AccessDeniedView();

            var advert = _advertisementService.GetAdvertisementById(id);
            if (advert == null)
                //No category found with the specified id
                return RedirectToAction("List");

            _advertisementService.DeleteAdvertisement(advert);

            //activity log
            _customerActivityService.InsertActivity("DeleteAdvert", _localizationService.GetResource("ActivityLog.DeleteAdvert"), advert.Name);

            SuccessNotification(_localizationService.GetResource("Admin.Advert.Advertisement.Deleted"));
            return RedirectToAction("List");
        }


        #endregion

        #region Utilities
        [NonAction]
        protected void UpdateLocales(Advertisement advert, AdvertisementModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(advert,
                                                               x => x.Name,
                                                               localized.Name,
                                                               localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(advert,
                                                           x => x.Description,
                                                           localized.Description,
                                                           localized.LanguageId);
            }
        }

        protected void PrepareAdvertType(AdvertisementModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            string[] advert = { "文字广告", 
                                "图片广告", 
                                "动画广告"};
            string[] advpot ={"全屏拉升","顶部大广告","顶部广告条","顶部1/2广告条","普通广告条","普通1/2广告条",
                              "全屏浮动广告条","左侧固定浮动","右侧固定浮动","左侧区域","右侧区域"};
            string[] advlevel = { "首页", "内页", "三级页", "末页" };
            for (int i=0;i<advert.Length;i++)
            {
                model.AvailableAdvertTypeTemplates.Add(new SelectListItem()
                {
                    Text = advert[i],
                    Value = (i+1).ToString()
                });
            }
            for (int j = 0; j < advpot.Length; j++)
            {
                model.AvailableAdverPositionTemplates.Add(new SelectListItem()
                {
                    Text = advpot[j],
                    Value = (j+ 1).ToString()
                });
            }
            for (int k = 0; k < advlevel.Length; k++)
            {
                model.AvailableAdverLevelTemplates.Add(new SelectListItem()
                {
                    Text = advlevel[k],
                    Value = (k + 1).ToString()
                });
            }
        }
        #endregion
    }
}
